package cn.xxm.service.impl;

import cn.xxm.mapper.SearchMapper;
import cn.xxm.pojo.ItemDoc;
import cn.xxm.pojo.RequestParams;
import cn.xxm.service.SearchService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.clients.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import org.apache.commons.lang.StringUtils;

import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.util.CollectionUtils;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;

import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Item> implements SearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemClient itemClient;


    @Override
    public List<String> getStringList(String key) {
        //准备request
        try {
            SearchRequest request = new SearchRequest("items");
            //准备DSL
            request.source().fetchSource(new String[0], null);
            request.source().suggest(new SuggestBuilder()
                    .addSuggestion("my_suggestion", SuggestBuilders.completionSuggestion("suggestion")
                            .size(10)
                            .skipDuplicates(true)
                            .prefix(key))
            );
            //发请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取suggestion
            CompletionSuggestion suggestion = response.getSuggest().getSuggestion("my_suggestion");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> list = new ArrayList<>(options.size());
            //遍历获取text
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().string());
            }

            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        //准备请求
        try {
            SearchRequest request = new SearchRequest("items");
            //2准备dsl
            buildBasicQuery(params, request);
            //设置size
            request.source().size(0);
            //聚合
            request.source().aggregation(AggregationBuilders
                    .terms("brandAgg")
                    .field("brand")
                    .size(50));
            request.source().aggregation(AggregationBuilders
                    .terms("categoryAgg")
                    .field("category")
                    .size(50));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> map = new HashMap<>(2);
            //4.1根据名称获取品牌聚合
            List<String> brandList = getAggByName(response, "brandAgg");
            List<String> categoryList = getAggByName(response, "categoryAgg");
            map.put("brand", brandList);
            map.put("category", categoryList);
            return map;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageDTO<ItemDoc> listAll(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("items");
            buildBasicQuery(params, request);
            if (!StringUtils.isBlank(params.getSortBy())) {
                if ("sold".equals(params.getSortBy())) {//按评价排序
                    request.source().sort(params.getSortBy(), SortOrder.DESC);
                }
                if ("price".equals(params.getSortBy())) {//按价格排序
                    request.source().sort(params.getSortBy(), SortOrder.ASC);
                }
            }
            //分页
            request.source().from(params.getPage() - 1).size(params.getSize());
            //高亮
            request.source().highlighter(
                    new HighlightBuilder().field("name").requireFieldMatch(false)
            );
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            PageDTO<ItemDoc> pageDTO = processResponse(response);
            return pageDTO;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public void getdownId(Long id) {
        try {

            DeleteRequest request = new DeleteRequest("items", id.toString());
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void getUpId(Long id) {
        try {
            Item item = itemClient.getById(id);
            ItemDoc itemDoc = new ItemDoc();
            BeanUtils.copyProperties(item,itemDoc);
            IndexRequest request = new IndexRequest("items").id(id.toString());
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageDTO<ItemDoc> processResponse(SearchResponse response) {
        PageDTO<ItemDoc> pageDTO = new PageDTO<>();
        //酒店数据集合
        List<ItemDoc> list = new ArrayList<>();
        //解析结果
        SearchHits searchHits = response.getHits();
        //获取文档总数量
        TotalHits total = searchHits.getTotalHits();
        pageDTO.setTotal(total.value);
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : searchHits) {
            //文档内容
            String json = hit.getSourceAsString();
            //将json格式转换为对象
            ItemDoc itemDoc = JSONObject.parseObject(json, ItemDoc.class);
            //高亮
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map!=null && map.size()>0){
                HighlightField field = map.get("name");
                String value = field.getFragments()[0].string();
                itemDoc.setName(value);
            }
            list.add(itemDoc);
        }
        pageDTO.setList(list);
        return pageDTO;

    }


    private List<String> getAggByName(SearchResponse response, String aggName) {
        List<String> brandList = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }


    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //对关键字搜索
        if (!StringUtils.isBlank(params.getKey())) {
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //过滤品牌
        if (!StringUtils.isBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //过滤分类
        if (!StringUtils.isBlank(params.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        //过滤价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(params.getMinPrice()*100)
                    .lte(params.getMaxPrice()*100));

        }
        //复合查询——算分函数查询
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery, //原始查询
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true), //过滤条件(符合条件的文档,重新打分)
                                ScoreFunctionBuilders.weightFactorFunction(10) //如何打分
                        )
                }
        ).boostMode(CombineFunction.SUM);//加权规则   新旧得分运算规则

        //设置整体查询
        request.source().query(functionScoreQueryBuilder);
    }
}